package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.UserLike;
import com.itheima.service.mongo.UserLikeService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author: Y F
 * @create: 2022-09-06 15:40
 */
@DubboService
public class UserLikeServiceImpl implements UserLikeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<UserLike> findAll(Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );

        return mongoTemplate.find(query, UserLike.class);
    }

    /**
     * 保存喜欢的数据
     * @param userLike
     */
    @Override
    public void save(UserLike userLike) {
        mongoTemplate.save(userLike);
    }

    /**
     * 判断是否互相喜欢
     * @param likeUserId
     * @param userId
     * @return
     */
    @Override
    public boolean isLove(Long userId,Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);
        Criteria criteria = new Criteria().orOperator(criteria1, criteria2);
        return mongoTemplate.count(Query.query(criteria), UserLike.class) == 2;
    }

    @Override
    public void delete(Long toUserId, long uid) {
        Query query = new Query(
                Criteria.where("likeUserId").is(uid).and("userId").is(toUserId)
        );
        mongoTemplate.remove(query, UserLike.class);
    }


}
